<template>
  <el-dialog
    v-model="dialogVisible"
    :title="editType == 'add' ? '新增' : '编辑'"
    width="30%"
    :before-close="close"
  >
    <main>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        status-icon
      >
        <el-form-item label="账户" prop="realname">
          <el-input v-model="ruleForm.realname" placeholder="请输入账户" clearable/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入电话" clearable/>
        </el-form-item>
      </el-form>
    </main>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue";

const dialogVisible = ref(false);
const editType = ref('add')
const ruleFormRef = ref();
const ruleForm = ref({
    realname: '',
    phone: '',
    id: ''
});
const rules = {
    realname: [
        { required: true, message: '账户不能为空!', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '电话不能为空！e', trigger: 'blur' },
        { min: 3, max: 11, message: 'Length should be 3 to 11', trigger: 'blur' },
    ],
};
/***
 * @method
 */

 const emit = defineEmits(['refreshPage'])

// 打开
const open = ({ realname, phone, id }, type) => {
    dialogVisible.value = true;
    editType.value = type
    ruleForm.value = {
        realname,
        phone,
        id
    }
};
// 关闭
const close = () => {
    dialogVisible.value = false;
};
// 确认
const confirm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (!valid) return
        // 如果id没值 说明是创建
        if (!ruleForm.value.id) {
            // 执行【新增】接口
        } else {
            // 执行【编辑】接口
        }

        // 执行成功刷新列表
        emit('refreshPage')
    })
};

defineExpose({
    close,
    open,
});
</script>
<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>
